using System.Collections.Generic;
using System.Threading.Tasks;
using Mvvm.Helpers;
using Mvvm.Models;
using SQLite;
// 引入 System.Linq 命名空间

namespace Mvvm.Services
{
    public class ChatDataStorage : IChatDataStorage
    {
        private const string DbName = "chatdatadb.sqlite3";
        public static readonly string ChatDataDbPath =
            PathHelper.GetLocalFilePath(DbName);

        private SQLiteAsyncConnection _connection;
        private SQLiteAsyncConnection Connection =>
            _connection ??= new SQLiteAsyncConnection(ChatDataDbPath);
        
        public async Task InitializeAsync()
        {
            await Connection.CreateTableAsync<ChatData>();
        }

        public async Task InsertAllAsync(List<ChatData> chatData, int identifier)
        {
            // 如果没有这个表，则调用初始化
            await InitializeAsync();
            foreach (var chat in chatData)
            {
                chat.Identifier = identifier;
            }
            await Connection.InsertAllAsync(chatData);
        }

        public async Task<List<ChatData>> ListAsync() => await Connection.Table<ChatData>().ToListAsync();

        //根据标识符查询
        public async Task<List<ChatData>> QueryAsync(int identifier) =>
            await Connection.Table<ChatData>()
                .Where(c => c.Identifier == identifier)
                .ToListAsync();

        public async Task DeleteAsync()
        {
            await Connection.DeleteAllAsync<ChatData>();
        }
    }
}